package com.bawei.module_mine.ui

import android.os.Bundle
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_common.mvi.base.BaseMVIActivity
import com.bawei.module_mine.databinding.ActivityConfirmOrderBinding
import com.bumptech.glide.Glide
import androidx.lifecycle.lifecycleScope
import com.bawei.module_mine.viewmodel.ConfirmOrderViewModel
import com.bawei.module_mine.intent.ConfirmOrderIntent
import com.bawei.module_mine.model.entity.*
import com.bawei.module_mine.state.ConfirmOrderState
import kotlinx.coroutines.launch
import android.content.Intent
import com.bawei.module_mine.model.entity.AddressEntity
import com.bawei.module_mine.model.service.AddressService
import androidx.recyclerview.widget.LinearLayoutManager

import com.bawei.module_goods.entity.ShoppingCartDisplayItem
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_mine.R
import com.bawei.module_mine.ui.ConfirmOrderProductAdapter

@Route(path = "/module_mine/ConfirmOrderActivity")
class ConfirmOrderActivity : BaseMVIActivity() {
    private lateinit var binding: ActivityConfirmOrderBinding
    private lateinit var confirmOrderViewModel: ConfirmOrderViewModel

    private var addressId: String? = null
    private var currentAddress: AddressEntity? = null
    private var productList: List<ShoppingCartDisplayItem> = emptyList()
    private lateinit var productAdapter: ConfirmOrderProductAdapter
    private var shipping: Double = 0.0

    override fun getLayoutRootView(): View {
        binding = ActivityConfirmOrderBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun generateViewModel() {
        confirmOrderViewModel = ConfirmOrderViewModel()
    }

    override fun initView() {
        super.initView()
        val cartItemsJson = intent.getStringExtra("cartItemsJson")
        if (!cartItemsJson.isNullOrEmpty()) {
            // 多商品/单商品统一模式
            val type = object : TypeToken<MutableList<ShoppingCartDisplayItem>>() {}.type
            productList = Gson().fromJson(cartItemsJson, type)
            productAdapter = ConfirmOrderProductAdapter(productList.toMutableList()) { position, newCount ->
                productAdapter.updateItemCount(position, newCount)
                refreshTotalPrice()
                requestShippingCost()
            }
            val recyclerView = findViewById<RecyclerView>(R.id.rv_product_list)
            recyclerView.layoutManager = LinearLayoutManager(this)
            recyclerView.adapter = productAdapter
            // 增加item间距
            recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: android.graphics.Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    outRect.bottom = 24 // 每个item底部间距24px，可根据实际调整
                }
            })
            refreshTotalPrice()
            // 地址未选中时自动加载默认地址
            if (addressId.isNullOrEmpty()) {
                loadDefaultAddress()
            } else {
                requestShippingCost()
            }
            // TODO: 组装请求参数并发送意图，需适配多商品
        } else {
            // 兼容老的单商品逻辑（如有需要）
            val goodsId = intent.getStringExtra("goodsId") ?: ""
            val goodsCode = intent.getStringExtra("goodsCode") ?: ""
            val goodsSkuId = intent.getStringExtra("goodsSkuId") ?: ""
            val goodsSkuCode = intent.getStringExtra("goodsSkuCode") ?: ""
            val number = intent.getIntExtra("number", 1)
            val price = intent.getIntExtra("price", 0)
            val modelName = intent.getStringExtra("modelName") ?: ""
            val mainImgUrl = intent.getStringExtra("mainImgUrl") ?: ""
            val goodsName = intent.getStringExtra("goodsName") ?: ""
            addressId = intent.getStringExtra("addressId")
            val couponCodes = intent.getStringArrayListExtra("couponCodes") ?: arrayListOf<String>()
            val payWay = intent.getStringExtra("payWay") ?: ""
            val remark = intent.getStringExtra("remark") ?: ""
            val orderType = intent.getStringExtra("orderType") ?: ""
            val businessType = intent.getStringExtra("businessType") ?: ""
            val dataId = intent.getStringExtra("dataId") ?: ""
            val channel = intent.getStringExtra("channel") ?: ""
            // 组装请求参数并发送意图（不再访问已删除控件）
            val goodsSkuDto = listOf(GoodsSkuDto(
                dataId = dataId.toIntOrNull(), 
                goodsSkuId = goodsSkuId.toIntOrNull(), 
                number = number
            ))
            val couponMaxDisReq = OrderCouponMaxDisRequest(
                businessType, 
                couponCodes, 
                goodsSkuDto, 
                dataId.toIntOrNull(), 
                payWay
            )
            lifecycleScope.launch {
                confirmOrderViewModel.intents.send(ConfirmOrderIntent.GetCouponMaxDis(couponMaxDisReq))
            }
            val cashDetailReq = OrderCashDetailRequest(
                addressId = addressId?.toLongOrNull(),
                couponCodes = couponCodes,
                goodsAddSkuDto = goodsSkuDto,
                dataId = dataId.toIntOrNull(),
                goodsCode = goodsCode,
                goodsId = goodsId.toIntOrNull(),
                goodsSkuCode = goodsSkuCode,
                goodsSkuId = goodsSkuId.toIntOrNull(),
                num = number,
                number = number,
                orderType = orderType,
                payWay = payWay,
                remark = remark
            )
            lifecycleScope.launch {
                confirmOrderViewModel.intents.send(ConfirmOrderIntent.GetOrderCashDetail(cashDetailReq))
            }
            val payCostTrialReq = OrderPayCostTrialRequest(
                addressId = addressId?.toLongOrNull(),
                couponCodes = couponCodes,
                goodsAddSkuDto = goodsSkuDto,
                dataId = dataId.toIntOrNull(),
                goodsCode = goodsCode,
                goodsId = goodsId.toIntOrNull(),
                goodsSkuCode = goodsSkuCode,
                goodsSkuId = goodsSkuId.toIntOrNull(),
                num = number,
                number = number,
                orderType = orderType,
                payChannel = payWay,
                payWay = payWay,
                remark = remark
            )
            lifecycleScope.launch {
                confirmOrderViewModel.intents.send(ConfirmOrderIntent.GetPayCostTrial(payCostTrialReq))
            }
            val couponSelectReq = OrderCouponSelectRequest(
                businessType = businessType,
                couponCodes = couponCodes,
                goodsSkuDto = goodsSkuDto,
                dataId = dataId.toIntOrNull(),
                payWay = payWay
            )
            lifecycleScope.launch {
                confirmOrderViewModel.intents.send(ConfirmOrderIntent.GetOrderCouponSelect(couponSelectReq))
            }
            val goodsInfoList = listOf(GoodsInfo(
                goodsId = goodsId.toIntOrNull(), 
                num = number, 
                price = price.toDouble()
            ))
            val shippingCostReq = OrderShippingCostRequestEntity(
                addressId = addressId?.toLongOrNull(),
                channel = channel,
                goodsInfoList = goodsInfoList
            )
            lifecycleScope.launch {
                confirmOrderViewModel.intents.send(ConfirmOrderIntent.GetShippingCost(shippingCostReq))
            }
            // 不再处理数量加减和商品信息控件
        }
        // 地址卡片点击跳转选择
        binding.cardAddress.setOnClickListener {
            val intent = Intent(this, AddressListActivity::class.java)
            startActivityForResult(intent, 1001)
        }
    }

    private fun refreshTotalPrice() {
        val items = productAdapter.getItems()
        val totalNum = items.sumOf { it.number }
        val totalPrice = items.sumOf { (it.price ?: 0.0) * it.number }
        binding.tvTotalPrice.text = "商品总价(共${totalNum}件) ¥%.2f".format(totalPrice)
        // 合计金额加上运费
        val finalTotal = totalPrice + shipping
        binding.tvFinalPrice.text = "合计 ¥%.2f".format(finalTotal)
        binding.tvBottomPrice.text = "¥%.2f".format(finalTotal)
    }

    private fun requestShippingCost() {
        val items = productAdapter.getItems()
        val goodsInfoList = items.map {
            GoodsInfo(
                goodsId = it.goodsId,
                num = it.number,
                price = it.price
            )
        }
        val shippingCostReq = OrderShippingCostRequestEntity(
            addressId = addressId?.toLongOrNull(),
            channel = "",
            goodsInfoList = goodsInfoList
        )
        lifecycleScope.launch {
            confirmOrderViewModel.intents.send(ConfirmOrderIntent.GetShippingCost(shippingCostReq))
        }
    }

    override fun handleState() {
        lifecycleScope.launch {
            confirmOrderViewModel.state.collect { state ->
                when (state) {
                    is ConfirmOrderState.CouponMaxDis -> {
                        val disAmount = state.data?.disAmount ?: 0.0
                        binding.tvCoupon.text = if (disAmount > 0) {
                            "优惠：¥$disAmount"
                        } else {
                            "暂无可用优惠券"
                        }
                    }
                    is ConfirmOrderState.OrderCashDetail -> {
                        // 可根据state.data?.cashDetailDtos展示支付方式
                    }
                    is ConfirmOrderState.PayCostTrial -> {
                        // 可根据state.data?.profitPrice展示手续费
                    }
                    is ConfirmOrderState.OrderCouponSelect -> {
                        // 可根据state.data?.availableCoupons展示推荐优惠券
                    }
                    is ConfirmOrderState.ShippingCost -> {
                        // 显示运费
                        shipping = state.data?.shippingPrice ?: 0.0
                        binding.tvShipping.text = if (shipping > 0) {
                            "配送  运费¥$shipping"
                        } else {
                            "配送  免运费"
                        }
                        refreshTotalPrice()
                    }
                    is ConfirmOrderState.Failed -> {
                        // 只在非技术性错误时显示提示
                        if (!state.msg.contains("HTTP") && !state.msg.contains("404")) {
                            showMsg(state.msg)
                        }
                    }
                    else -> {}
                }
            }
        }
    }

    // 加载默认地址（自动补全实现）
    private fun loadDefaultAddress() {
        val service = AddressService()
        lifecycleScope.launch {
            val list = try { service.getAddressList().data } catch (e: Exception) { null }
            val defaultAddr = list?.find { it.isDefault == 1 } ?: list?.firstOrNull()
            showAddress(defaultAddr)
            addressId = defaultAddr?.id?.toString()
            requestShippingCost()
        }
    }

    // 加载指定地址
    private fun loadAddressById(id: String) {
        val service = AddressService()
        lifecycleScope.launch {
            val list = try { service.getAddressList().data } catch (e: Exception) { null }
            val addr = list?.find { it.id.toString() == id }
            showAddress(addr)
            addressId = addr?.id?.toString()
            refreshOrderRelatedData()
        }
    }

    // 回显地址信息
    private fun showAddress(address: AddressEntity?) {
        currentAddress = address
        if (address == null) {
            binding.tvAddressNamePhone.text = "添加收货地址"
            binding.tvAddressDetail.visibility = View.GONE
        } else {
            binding.tvAddressNamePhone.text = "${address.receiverName}  ${address.receiverPhone}"
            binding.tvAddressDetail.text = "${address.provinceName.orEmpty()}${address.cityName.orEmpty()}${address.districtName.orEmpty()}${address.address.orEmpty()}"
            binding.tvAddressDetail.visibility = View.VISIBLE
        }
    }

    // 选择地址回调
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1001 && resultCode == RESULT_OK) {
            val address = data?.getParcelableExtra<AddressEntity>("address")
            if (address != null) {
                showAddress(address)
                addressId = address.id?.toString()
                requestShippingCost()
            }
        }
    }

    // addressId变化时，自动刷新运费、下单等相关接口
    private fun refreshOrderRelatedData() {
        // 重新组装请求体并发送意图，addressId 用最新的
        // ...可复用原有的意图发送逻辑，只需将 addressId 替换为最新值
        // 例如：
        // val shippingCostReq = OrderShippingCostRequestEntity(addressId = addressId?.toLongOrNull(), ...)
        // confirmOrderViewModel.intents.send(ConfirmOrderIntent.GetShippingCost(shippingCostReq))
    }
} 